<template>
  <!-- 题库批量更换章节 -->
  <el-dialog :visible.sync="localVisible" :title="title" width="600px" @close="handleClose"
    :close-on-click-modal="false" append-to-body @open="handleOpen">
    <!-- <div class="dialog-content"> -->
    <el-form :model="formData" label-width="100px">
      <!-- 题型选择 -->
      <el-row>
        <el-col :span="24">
          <h3> <span class="markRed">*</span>试题类型</h3>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-radio-group v-model="formData.type">
            <el-radio :label="1">单选题</el-radio>
            <!-- <el-radio label="multipleChoice">多选题</el-radio> -->
            <!-- <el-radio label="judgment">判断题</el-radio> -->
            <!-- 其他题型... -->
          </el-radio-group>
        </el-col>
      </el-row>

      <!-- 题目内容 -->
      <el-row>
        <el-col :span="24">
          <h3><span class="markRed">*</span>试题题目</h3>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-input v-model="formData.topic" placeholder="请输入试题题目" size="mini" style="width: 400px;"></el-input>
        </el-col>
      </el-row>

      <!-- 试题选项 -->
      <el-row>
        <el-col :span="24">
          <h3><span class="markRed">*</span>试题选项</h3>
        </el-col>
      </el-row>
      <el-row v-for="(option, index) in formData.options" :key="index">
        <el-col :span="1" style="display: flex; align-items: center; justify-content: center;">
          <span>{{ option.key }}.</span>
        </el-col>
        <el-col :span="10">
          <el-input v-model="option.value" placeholder="请输入试题选项" size="mini"></el-input>
        </el-col>
        <el-col :span="2">
          <el-button @click="removeOption(index)" icon="el-icon-delete" type="text"
            style="margin-left: 10px; "></el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" v-if="formData.options.length < 6">
          <el-button type="primary" size="mini" @click="addOption" style="margin-top: 20px;">添加选项</el-button>
        </el-col>
      </el-row>

      <!-- 答案 -->
      <el-row>
        <el-col :span="24">
          <h3><span class="markRed">*</span>答案</h3>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-radio-group v-model="formData.answer" v-if="formData.type == '1'">
            <el-radio v-for="(option, index) in formData.options" :key="index" :label="option.key">
              {{ option.key }}
            </el-radio>
          </el-radio-group>
        </el-col>
      </el-row>

      <!-- 选择章节 -->
      <el-row>
        <el-col :span="24">
          <h3>选择章节</h3>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-select v-model="formData.fk_t_sctk_chapter_id" placeholder="请选择">
            <el-option v-for="item in flatChapters" :key="item.id" :label="item.name" :value="item.id">
              <span :style="{ paddingLeft: item.level * 20 + 'px' }">{{ item.name }}</span>
            </el-option>

          </el-select>
          <el-button type="primary" @click="editChapter" size="mini" style="margin-left: 10px;">编辑章节</el-button>
          <el-switch v-model="formData.chapterCheck" active-text="章节检测" style="margin-left: 10px;"></el-switch>
        </el-col>
      </el-row>

      <!-- 难易程度 -->
      <el-row>
        <el-col :span="24">
          <h3>难易程度</h3>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-select v-model="formData.difficulty" placeholder="请选择">
            <el-option label="简单" :value="1"></el-option>
            <el-option label="容易" :value="2"></el-option>
            <el-option label="适中" :value="3"></el-option>
            <el-option label="困难" :value="4"></el-option>
            <el-option label="极难" :value="5"></el-option>
          </el-select>
        </el-col>
      </el-row>

      <!-- 提交按钮 -->
      <!-- <el-row>
          <el-col :span="24">
            <el-button type="primary" size="mini" style="margin-top: 20px;">录入试题</el-button>
             
          </el-col>
        </el-row> -->
      <el-row>
        <el-col :span="24" style="text-align: right; margin-top: 20px;">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="btnOk">确定</el-button>
        </el-col>
      </el-row>
      <update-chapter :show-dialog.sync="updateChapterShowDialog" :title="updateChapterdialogTitle"
        :fk_t_sctk_id="fk_t_sctk_id" :chapters="chapters" @chapter-updated="getChapters"></update-chapter>
    </el-form>

    <!-- </div> -->
  </el-dialog>
</template>

<script>
import { getQuesstionBankDetails, addQuesstionBank } from '@/api/quesstionBank';
import { getSctktChapterList } from '@/api/sctkChapter'
import updateChapter from '@/components/updateChapter'
import { transListToTreeDataOnChapter } from '@/utils'
export default {
  name: 'updateQuestion',
  components: {
    updateChapter
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false,
      required: true
    },
    title: {
      type: String,
      default: '编辑题目'
    },

    fk_t_sctk_question_id: {
      type: Number,
      required: true
    },
    fk_t_sctk_id: {
      type: Number,
      required: true
    }
  },
  computed: {
    // 将嵌套数据转换为扁平数组
    flatChapters() {
      const result = [];
      function flatten(items, level = 0) {
        for (const item of items) {
          const newItem = { ...item, level }; // 添加层级信息
          result.push(newItem);
          if (item.children && item.children.length > 0) {
            flatten(item.children, level + 1); // 递归处理子级
          }
        }
      }
      flatten(this.chapters); // 开始扁平化处理
      return result;
    }
  },
  data() {
    return {
      localVisible: this.showDialog,
      chapters: [

      ],
      chapterCheck: false,
      formData: {
        type: 1,
        topic: '',
        options: [],
        answer: '',
        fk_t_sctk_chapter_id: null,
        difficulty: 3,
        chapterCheck: 0
      },
      updateChapterShowDialog: false,
      updateChapterdialogTitle: '编辑章节'
    };
  },
  watch: {
    showDialog(newVal) {
      this.localVisible = newVal;
    },
    localVisible(newVal) {
      if (newVal !== this.showDialog) {

        this.$emit('update:showDialog', newVal);
      }
    },
    updateChapterShowDialog(newVal) {
      if (!newVal) {
        this.getChapters(); // 当子弹窗关闭时刷新章节列表
      }
    }
  },
  methods: {
    // 打开弹层发送请求 代替create()
    handleOpen() {

      this.getQuesstionBankDetails()
      this.getChapters();
    },
    async getQuesstionBankDetails() {
      // 示例：根据 questionId 请求数据
      const data = await getQuesstionBankDetails({ id: this.fk_t_sctk_question_id });
      this.formData = data;
      if (data.options) {

        this.formData.options = this.parseOptions(data.options);
      }

    },
    async getChapters() {
      let result = await getSctktChapterList({ fk_t_sctk_id: this.fk_t_sctk_id })
      // 递归处理
      this.chapters = transListToTreeDataOnChapter(result, 0)

    },
    handleClose() {
      this.localVisible = false;
      this.formData = {
        type: 1,
        topic: '',
        options: [],
        answer: '',
        fk_t_sctk_chapter_id: null,
        difficulty: 3,
        chapterCheck: 0
      }
    },
    // 编辑章节
    editChapter() {
      this.updateChapterShowDialog = true
      this.updateChapterdialogTitle = '编辑章节'

    },
    async btnOk() {
      // 1️⃣ 表单校验
      if (!this.formData.topic.trim()) {
        this.$message.warning('试题题目不能为空');
        return;
      }

      if (!this.formData.options || this.formData.options.length < 2) {
        this.$message.warning('至少需要两个选项');
        return;
      }

      if (!this.formData.answer) {
        this.$message.warning('请选择答案');
        return;
      }

      try {
        // 2️⃣ 数据格式化
        const submitData = {
          ...this.formData
        };

        // 3️⃣ 调用接口保存
        await addQuesstionBank(submitData);

        // 4️⃣ 成功提示 + 关闭弹窗
        this.$message.success('编辑成功');
        // 通知父组件更新
        this.$emit('submit')
        //重置表单
        this.handleClose()

      } catch (error) {
        console.error('保存失败', error);
        this.$message.error('保存失败，请重试');
      }
    },
    parseOptions(options) {
      if (typeof options === 'string') {
        options = JSON.parse(options);  // 把字符串转成数组
      }
      if (!options || !Array.isArray(options)) {

        return [];
      }

      return options.map(option => ({
        key: option.key,
        value: option.value
      }));
    },
    removeOption(index) {
      if (!this.formData.options || this.formData.options.length <= 2) {
        this.$message.warning('至少需要两个选项');
        return;
      }

      this.formData.options.splice(index, 1);
      // 重新生成选项字母
      const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      let newOptions = [];

      for (let i = 0; i < this.formData.options.length; i++) {
        let option = this.formData.options[i];
        let newLabel = alphabet[i];
        newOptions.push({ key: newLabel, value: option.value });
      }

      // 更新 question.options
      this.formData.options = newOptions;
      // this.formData.options.splice(index, 1);
    },
    addOption() {
      const nextKey = this.getNextOptionKey();
      this.formData.options.push({ key: nextKey, value: '' });
    },
    //获取下一个选项key
    getNextOptionKey() {
      const existingKeys = this.formData.options.map(opt => opt.key);
      for (let i = 0; i < 26; i++) {
        const key = String.fromCharCode(65 + i); // A-Z
        if (!existingKeys.includes(key)) {
          return key;
        }
      }
      return null; // 超过 Z 返回 null
    },

  },

};
</script>

<style scoped>
.dialog-content {
  display: flex;
  flex-direction: column;

  height: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  width: 100%;
}

.quill-editor {
  height: 150px;
}

.el-button--circle {
  padding: 8px;
}

h3 {
  font-size: 16px;
  /* 设置与普通文本相同的字体大小 */
  font-weight: normal;
  /* 不加粗 */
  margin-bottom: 20px;
  /* 调整上下间距 */
}

.markRed {
  font-size: 14px;
  color: red;
  text-align: center;
  margin-right: 5px;
}
</style>